var express = require('express');
var router = express.Router();
var crypto = require("crypto")
let userService = require('../service/userinfoService')
let jwt = require('jsonwebtoken')

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.post('/login', async (req, res, next) => {
  let { username, userpwd } = req.body

  let md5 = crypto.createHash('md5')
  userpwd = md5.update(userpwd).digest('hex');

  let result = await userService.login({
    username,
    userpwd
  })
  if (result.length) {
    //表示存在
    let info = result[0];//做设计的时候 会让用户名唯一

    let token = jwt.sign({
      userid: info._id,
      username: info.username,
      usertype: info.usertype
    }, '2215', {
      expiresIn: 1000 * 60 * 30
    })


    res.json({
      code: 200,
      msg: '登录成功',
      token,
      menu: info.usertype == 1 ? '老师' : '学生'
    })
  } else {
    res.json({
      code: 203,
      msg: '用户名和密码不匹配'
    })
  }

})

router.post('/registe', (async (req, res, next) => {
  let { username, userpwd, usertype, } = req.body

  let md5 = crypto.createHash('md5')
  userpwd = md5.update(userpwd).digest('hex')
  //接口可以接收数据
  let result = await userService.add([{ username, userpwd, usertype }])
  //需要把数据写入数据库
  res.json({
    code: 200,
    result
  })
}))
module.exports = router;
